package com.fbty.mt.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.fbty.base.dao.MtJdbcDao;
import com.fbty.base.domain.Page;
import com.fbty.mt.dao.OnlyIpInfoDao;
import com.fbty.mt.dao.TabIpLogDao;
import com.fbty.mt.dao.UserDao;
import com.fbty.mt.dao.UserIpInfoDao;
import com.fbty.mt.domain.AccountInfo;
import com.fbty.mt.domain.CheckInfo;
import com.fbty.mt.domain.OnlyIpInfo;
import com.fbty.mt.domain.TabIpLog;
import com.fbty.mt.domain.User;
import com.fbty.mt.domain.UserIpInfo;
import com.fbty.mt.service.ProxyService;
import com.fbty.mt.service.UserIpInfoService;
import com.fbty.mt.utils.DateTool;
import com.fbty.mt.utils.OnlyCodeUtil;

public class UserIpInfoServiceImpl implements UserIpInfoService {

	private MtJdbcDao mtJdbcDao;

	private UserIpInfoDao userIpInfoDao;

	private OnlyIpInfoDao onlyIpInfoDao;

	private ProxyService proxyService;

	private UserDao userDao;
	private TabIpLogDao tabIpLogDao;

	@Override
	public int updateUseNum(int uid) {
		/*
		 * String querysql = " SELECT COUNT(*) FROM tab_user_ip up "+
		 * " WHERE flag=? AND uid=?";
		 */
		String updateSql = "UPDATE tab_user_ip SET flag=? WHERE flag=? and uid=?";
		// int num = mtJdbcDao.getJdbcTemplate().queryForInt(querysql,new
		// Object[]{false,uid});
		int num = mtJdbcDao.getJdbcTemplate().update(updateSql,
				new Object[] { true, false, uid });
		return num;
	}

	@Override
	public void saveMyIpInfo(UserIpInfo userIpInfo, int num, boolean flag) {
		try {
			if (flag) {
				String sql = "update tab_user set monthnum=? where id= ?";
				int i = mtJdbcDao.getJdbcTemplate().update(sql,
						new Object[] { (num - 1), userIpInfo.getUid() });
			} else {
				String sql = "update tab_user set num=? where id= ?";
				int i = mtJdbcDao.getJdbcTemplate().update(sql,
						new Object[] { (num - 1), userIpInfo.getUid() });
			}
			userIpInfoDao.save(userIpInfo);
			User user = userDao.get(userIpInfo.getUid());

			TabIpLog tabIpLog = new TabIpLog();
			tabIpLog.setUid(userIpInfo.getUid());
			tabIpLog.setBuyTime(new Date());
			tabIpLog.setBuyNum(1);
			tabIpLog.setMonthNum(user.getMonthnum());
			tabIpLog.setNum(user.getNum());
			tabIpLogDao.save(tabIpLog);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setMtJdbcDao(MtJdbcDao mtJdbcDao) {
		this.mtJdbcDao = mtJdbcDao;
	}

	public void setOnlyIpInfoDao(OnlyIpInfoDao onlyIpInfoDao) {
		this.onlyIpInfoDao = onlyIpInfoDao;
	}

	public void setUserIpInfoDao(UserIpInfoDao userIpInfoDao) {
		this.userIpInfoDao = userIpInfoDao;
	}

	@Override
	public boolean repeat(int ipid, int uid) {

		String sql = "SELECT COUNT(id) FROM tab_user_ip WHERE ipid=? AND uid = ?";
		int i = mtJdbcDao.getJdbcTemplate().queryForInt(sql,
				new Object[] { ipid, uid });

		return i == 0 ? true : false;
	}

	@Override
	public Page queryShareIp(int pageNo, int pageSize, String state, int uid,
			String type, String country, String region, String city) {
		String sql = " SELECT up.id,ti.country,ti.region,ti.city,up.endTime,ti.type as type,ti.port,ti.ip,ti.state"
				+ " FROM  tab_user_ip up,tab_ip_info ti"
				+ " WHERE up.iptype=0 and up.ipid=ti.id AND up.uid=? and ti.state like ? and "
				+ " type like ? and country like ?  and region like ?  and city like ? "
				+ " order by up.id desc";
		Page page = mtJdbcDao.getMysqlJdbcTemplate().queryPageMap(sql, pageNo,
				pageSize,
				new Object[] { uid, state, type, country, region, city });
		return page;
	}

	@Override
	public Page queryOnlyIp(int pageNo, int pageSize, String state, int uid,
			String type, String country, String region, String city) {
		String sql = " SELECT up.id,ti.country,ti.region,ti.city,up.endTime,ti.type as type,ti.id as ipid,ti.speed,"
				+ " ti.entranceIp,ti.entrancePort,ti.exportIp,ti.exportPort,ti.state,up.username,up.password,ti.proxyType,up.autoChange"
				+ " FROM  tab_user_ip up,tab_only_ip_info ti"
				+ " WHERE up.iptype=1 and up.ipid=ti.id AND up.uid=? and ti.state like ? and "
				+ " type like ? and country like ?  and region like ?  and city like ? "
				+ " order by up.id desc";
		Page page = mtJdbcDao.getMysqlJdbcTemplate().queryPageMap(sql, pageNo,
				pageSize,
				new Object[] { uid, state, type, country, region, city });
		return page;
	}

	@Override
	public void saveMyOnlyIp(UserIpInfo userIpInfo) {
		String sql = "UPDATE tab_record SET state=2 WHERE uid=? AND buyDate = (SELECT * FROM (SELECT MIN(r.buyDate) FROM tab_record r,tab_price p WHERE r.uid=? AND r.pid=p.id AND p.type=3 AND r.state=1) t)";

		int num = mtJdbcDao.getJdbcTemplate().update(sql,
				new Object[] { userIpInfo.getUid(), userIpInfo.getUid() });

		String onlyIpSql = "UPDATE tab_only_ip_info SET state=1 WHERE id=?";
		mtJdbcDao.getJdbcTemplate().update(onlyIpSql,
				new Object[] { userIpInfo.getIpid() });
		userIpInfoDao.save(userIpInfo);
	}

	@Override
	public int queryIpState(int ipid) {
		String sql = "SELECT state FROM tab_only_ip_info WHERE id = ?";

		int i = mtJdbcDao.getJdbcTemplate().queryForInt(sql,
				new Object[] { ipid });

		return i;
	}

	@Override
	public OnlyIpInfo findIpById(int ipid) throws Exception {

		return onlyIpInfoDao.get(ipid);
	}

	@Override
	public Map<String, Object> findMsg(int id) throws Exception {
		String sql = " SELECT  ti.entranceIp,ti.country,ti.region,ti.city,ti.speed,ti.type,ti.uploadTime,"
				+ " ti.used,ti.entrancePort,ti.proxyType,"
				+ " ti.username,ti.password,ui.endTime,ui.num"
				+ " FROM  tab_user_ip ui   LEFT JOIN tab_only_ip_info ti"
				+ " ON  ui.ipid = ti.id " + " WHERE ui.iptype=1 AND ui.id=?";

		Map<String, Object> map = mtJdbcDao.getJdbcTemplate().queryForMap(sql,
				new Object[] { id });
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		map.put("uploadTime", sdf.format(map.get("uploadTime")));
		map.put("endTime", sdf.format(new Date((Long) map.get("endTime"))));
		return map;
	}

	@Override
	public UserIpInfo findUserIpById(int id) throws Exception {

		return userIpInfoDao.get(id);
	}

	@Override
	public void modifyUserIpInfo(UserIpInfo userIpInfo) throws Exception {
		userIpInfoDao.update(userIpInfo);
	}

	@Override
	public int modifyOnlyIP(UserIpInfo ipInfo, OnlyIpInfo info)throws Exception {
		int state = 0;
		
		ipInfo.setIpid(info.getId());
		ipInfo.setIptype(1);
		ipInfo.setNum(0);
		ipInfo.setUsername(OnlyCodeUtil.randomUsername());
		ipInfo.setPassword(OnlyCodeUtil.randomPassword());
		
		// 添加到代理机上
		AccountInfo aif = proxyService.creatAccount(ipInfo.getUsername(), ipInfo
				.getPassword(), DateTool.parseDateToString(
				new Date(ipInfo.getEndTime()), "yyyy-MM-dd"), DateTool
				.parseDateToString(new Date(ipInfo.getEndTime()), "HH:mm:ss"),
				info.getExportIp(), info.getExportPort());

		if (aif.getResult() == 1) {
			info.setState(1);// 修改为已经购买
			info.setEntranceIp(aif.getHost());
			info.setEntrancePort(aif.getPort());
			onlyIpInfoDao.update(info);
		}
		ipInfo.setAutoChange(true);
		userIpInfoDao.update(ipInfo);
		state = 1;

		return state;
	}

	public void setProxyService(ProxyService proxyService) {
		this.proxyService = proxyService;
	}

	@Override
	public Page queryAllUserIp(int pageNo, int pageSize,
			Map<String, String> map, Map<String, String> likeMap)
			throws Exception {
		StringBuffer sb = new StringBuffer(
				"SELECT ui.id as uid,u.username,oi.entranceIp,oi.entrancePort,oi.exportIp,oi.exportPort,oi.id,");
		sb.append(" oi.country,oi.region,oi.city,ui.endTime,oi.type,oi.used,ui.autoChange");
		StringBuffer sc = new StringBuffer("select count(*) ");
		sb.append(" FROM tab_user u,tab_only_ip_info oi,tab_user_ip ui");
		sc.append(" FROM tab_user u,tab_only_ip_info oi,tab_user_ip ui");
		sb.append(" WHERE ui.ipid=oi.id AND ui.iptype=1 AND ui.uid=u.id");
		sc.append(" WHERE ui.ipid=oi.id AND ui.iptype=1 AND ui.uid=u.id");
		for (Entry<String, String> entry : map.entrySet()) {
			sb.append(" and " + entry.getKey() + "= '" + entry.getValue() + "'");
			sc.append(" and " + entry.getKey() + "= '" + entry.getValue() + "'");
		}
		for (Entry<String, String> entry : likeMap.entrySet()) {
			sb.append(" and " + entry.getKey() + "like '" + entry.getValue()
					+ "'");
			sc.append(" and " + entry.getKey() + "like '" + entry.getValue()
					+ "'");
		}
		sb.append(" limit " + (pageNo - 1) * pageSize + "," + pageSize);
		int count = mtJdbcDao.getJdbcTemplate().queryForInt(sc.toString());
		List<Map<String, Object>> list = mtJdbcDao.getJdbcTemplate()
				.queryForList(sb.toString());
		return new Page(list, (pageNo - 1) * pageSize, count, pageSize);
	}

	@Override
	public void modifyEndTimeIp() throws Exception {
		String sql = "SELECT id,ipid FROM tab_user_ip WHERE iptype=1 AND  flag = 0 and endTime<"
				+ System.currentTimeMillis();
		List<Map<String, Object>> list = mtJdbcDao.getJdbcTemplate()
				.queryForList(sql);
		if (list.size() > 0) {
			StringBuffer uipSql = new StringBuffer(
					"update tab_user_ip set flag=1 where id in (");
			StringBuffer oipSql = new StringBuffer(
					"update tab_only_ip_info set state=0 where id in (");
			for (Map<String, Object> map : list) {
				uipSql.append(map.get("id") + ",");
				oipSql.append(map.get("ipid") + ",");
			}
			uipSql = new StringBuffer(uipSql.substring(0, uipSql.length() - 1))
					.append(")");
			oipSql = new StringBuffer(oipSql.substring(0, oipSql.length() - 1))
					.append(")");
			;
			mtJdbcDao.getJdbcTemplate().execute(uipSql.toString());
			mtJdbcDao.getJdbcTemplate().execute(oipSql.toString());
		}
	}

	@Override
	public void modifyAutoChange(int upid, int ipid) throws Exception {
		UserIpInfo uip = userIpInfoDao.get(upid);
		uip.setAutoChange(true);
		OnlyIpInfo onlyIpInfo = onlyIpInfoDao.get(ipid);
		UserIpInfo nuip = new UserIpInfo();
		nuip.setAutoChange(false);
		nuip.setEndTime(uip.getEndTime());
		nuip.setFlag(false);
		nuip.setIptype(1);
		nuip.setPassword(OnlyCodeUtil.randomUsername());
		nuip.setUsername(OnlyCodeUtil.randomPassword());
		nuip.setUid(uip.getUid());
		nuip.setNum(0);
		nuip.setIpid(ipid);
		AccountInfo aif = proxyService.creatAccount(nuip.getUsername(), nuip
				.getPassword(), DateTool.parseDateToString(
				new Date(nuip.getEndTime()), "yyyy-MM-dd"), DateTool
				.parseDateToString(new Date(nuip.getEndTime()), "HH:mm:ss"),
				onlyIpInfo.getExportIp(), onlyIpInfo.getExportPort());
		if (aif.getResult() == 1) {
			onlyIpInfo.setEntranceIp(aif.getHost());
			onlyIpInfo.setEntrancePort(aif.getPort());
			onlyIpInfo.setUsername(aif.getUser());
			onlyIpInfo.setPassword(aif.getPassword());
			onlyIpInfo.setState(1);// 修改为已经购买
			onlyIpInfoDao.update(onlyIpInfo);
		} else {
			throw new RuntimeException("更换失败！");
		}
		userIpInfoDao.update(uip);
		userIpInfoDao.save(nuip);
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public TabIpLogDao getTabIpLogDao() {
		return tabIpLogDao;
	}

	public void setTabIpLogDao(TabIpLogDao tabIpLogDao) {
		this.tabIpLogDao = tabIpLogDao;
	}

}
